package com.cskaoyan.service.wx.impl;/*-*- coding = utf-8 -*-
@Time : 2022/11/22 20:42
@Author : 林涂兵
@File : WxOrderServiceImpl.java
@Software: IntelliJ IDEA*/


import com.cskaoyan.bean.bo.OrderSubmitBo;
import com.cskaoyan.bean.common.BaseParam;
import com.cskaoyan.bean.po.MarketOrder;
import com.cskaoyan.bean.po.MarketOrderExample;
import com.cskaoyan.bean.po.MarketOrderGoods;
import com.cskaoyan.bean.po.MarketOrderGoodsExample;
import com.cskaoyan.bean.vo.HandleOptionVo;
import com.cskaoyan.bean.vo.OrderList2Vo;
import com.cskaoyan.bean.vo.OrderListVo;
import com.cskaoyan.bean.vo.wx.OrderDetailVo;
import com.cskaoyan.bean.vo.wx.OrderInfoVo;
import com.cskaoyan.bean.vo.wx.OrderSubmitVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.wx.WxOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.cskaoyan.bean.bo.wxordercommentbo.OrderCommentBo;
import com.cskaoyan.bean.po.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;

    @Autowired
    ShipChannelMapper shipChannelMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;


    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketUserMapper marketUserMapper;


    @Override
    public OrderListVo selectOrderByStatusId(BaseParam baseParam, Integer showType) {
        OrderListVo orderListVo = new OrderListVo();
        ArrayList<OrderList2Vo> orderList2Vos = new ArrayList<>();

        Short orderStatus = null;
        switch (showType) {
            case 0:
                break;
            case 1:
                orderStatus = 101;
                break;
            case 2:
                orderStatus = 201;
                break;
            case 3:
                orderStatus = 301;
                break;
            case 4:
                orderStatus = 402;
                break;
        }

        // 开启分页
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());


        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();

        // 不显示已删除的订单
        criteria.andDeletedEqualTo(false);


        // 降序排列
        marketOrderExample.setOrderByClause("update_time desc" );


        if (orderStatus == null) {
            criteria.andOrderStatusIsNotNull();
        } else {
            criteria.andOrderStatusEqualTo(orderStatus);
        }
        // 获取对应的订单
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);

        PageInfo<MarketOrder> marketOrderPageInfo = new PageInfo<>(marketOrders);

        orderListVo.setPage(baseParam.getPage());
        orderListVo.setPages(marketOrderPageInfo.getPages());
        orderListVo.setTotal(marketOrderPageInfo.getTotal());
        // 根据订单id获取对应的商品，以及为handOption赋值
        for (MarketOrder marketOrder : marketOrders) {
            OrderList2Vo list2Vo = new OrderList2Vo();

            Integer orderId = marketOrder.getId();
            // 根据订单id获取对应的商品
            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
            List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);

            list2Vo.setGoodsList(marketOrderGoods);


            Short status = marketOrder.getOrderStatus();
            HandleOptionVo handleOptionVo = new HandleOptionVo();
            switch (status) {
                case 101:
                    handleOptionVo.setCancel(true);
                    list2Vo.setOrderStatusText("未付款");
                    break;
                case 201:
                    handleOptionVo.setRefund(true);
                    list2Vo.setOrderStatusText("待发货");
                    break;
                case 301:
                    handleOptionVo.setComment(true);
                    list2Vo.setOrderStatusText("待收货");
                    break;
                case 402:
                    handleOptionVo.setComment(true);
                    Short comments = 1;
                    if (marketOrder.getComments().equals(comments)){
                        list2Vo.setOrderStatusText("已评价");
                    }else {
                        list2Vo.setOrderStatusText("待评价");
                    }
                    break;
                default:
                    list2Vo.setOrderStatusText("已知悉");
            }

            list2Vo.setHandleOptions(handleOptionVo);
            list2Vo.setActualPrice(marketOrder.getActualPrice());
            list2Vo.setAftersaleStatus(marketOrder.getAftersaleStatus());
            list2Vo.setOrderSn(marketOrder.getOrderSn());
            list2Vo.setId(marketOrder.getId());
            list2Vo.setIsGroupIn(0);

            orderList2Vos.add(list2Vo);
        }


        orderListVo.setList(orderList2Vos);

        return orderListVo;
    }

    // 根据订单id查询对应的订单详情
    @Override
    public OrderDetailVo selectOrderDetailById(Integer orderId) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();

        // 获取订单
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        // 获取订单中的商品信息
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(marketOrderGoodsExample);

        orderDetailVo.setOrderGoods(marketOrderGoods);

        // 获取详细信息
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setActualPrice(marketOrder.getActualPrice());
        orderInfoVo.setAddress(marketOrder.getAddress());
        orderInfoVo.setAddTime(marketOrder.getAddTime());
        orderInfoVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfoVo.setConsignee(marketOrder.getConsignee());
        orderInfoVo.setCouponPrice(marketOrder.getCouponPrice());
        orderInfoVo.setFreightPrice(marketOrder.getFreightPrice());
        orderInfoVo.setId(marketOrder.getId());
        orderInfoVo.setMessage(marketOrder.getMessage());
        orderInfoVo.setOrderSn(marketOrder.getOrderSn());
        orderInfoVo.setExpCode(marketOrder.getShipChannel());
        orderInfoVo.setExpNo(marketOrder.getShipSn());
        orderInfoVo.setGoodsPrice(marketOrder.getGoodsPrice());
        orderInfoVo.setMobile(marketOrder.getMobile());


        String name = shipChannelMapper.selectNameByCode(marketOrder.getShipChannel());
        orderInfoVo.setExpName(name);

        HandleOptionVo handleOptionVo = new HandleOptionVo();

        Short status = marketOrder.getOrderStatus();


        switch (status) {
            case 101:
                handleOptionVo.setCancel(true);
                handleOptionVo.setPay(true);
                orderInfoVo.setOrderStatusText("未付款");
                break;
            case 201:
                handleOptionVo.setRefund(true);
                orderInfoVo.setOrderStatusText("待发货");
                break;
            case 301:
                handleOptionVo.setConfirm(true);
                orderInfoVo.setOrderStatusText("待收货");
                break;
            case 402:
                Short comments = marketOrder.getComments();
                handleOptionVo.setRebuy(true);
                handleOptionVo.setAftersale(true);
                handleOptionVo.setDelete(true);
                // 根据评论状态开启评论
                if (comments == 1){

                    orderInfoVo.setOrderStatusText("已评价");
                }else {
                    handleOptionVo.setComment(true);
                    orderInfoVo.setOrderStatusText("未评价");
                }
                break;
        }
        orderInfoVo.setHandleOption(handleOptionVo);

        orderDetailVo.setOrderInfo(orderInfoVo);
        return orderDetailVo;
    }


    @Override
    public int orderConfirm(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        short status = 402;
        marketOrder.setOrderStatus(status);
        marketOrder.setConfirmTime(new Date());
        marketOrder.setUpdateTime(new Date());
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int code = marketOrderMapper.updateByExampleSelective(marketOrder, marketOrderExample);
        return code;
    }

    @Override
    public int orderRefund(Integer orderId) {
        MarketOrder orderByPrimaryKey = marketOrderMapper.selectByPrimaryKey(orderId);
        BigDecimal actualPrice = orderByPrimaryKey.getActualPrice();
        MarketOrder marketOrder = new MarketOrder();
        short status = 202;
        marketOrder.setOrderStatus(status);
        marketOrder.setRefundAmount(actualPrice);
        marketOrder.setRefundTime(new Date());
        marketOrder.setUpdateTime(new Date());
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int code = marketOrderMapper.updateByExampleSelective(marketOrder, marketOrderExample);
        return code;
    }

    @Override
    public int orderDelete(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setDeleted(true);
        marketOrder.setEndTime(new Date());
        marketOrder.setUpdateTime(new Date());
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int code = marketOrderMapper.updateByExampleSelective(marketOrder, marketOrderExample);
        return code;
    }

    @Override
    public MarketOrderGoods orderGoods(Integer orderId, Integer goodsId) {
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByOrderIdAndGoodsId(orderId, goodsId);
        return marketOrderGoods;
    }

    @Override
    @Transactional
    public int orderComment(OrderCommentBo orderCommentBo) {
        Subject subject = SecurityUtils.getSubject();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectById(orderCommentBo.getOrderGoodsId());
        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(marketOrderGoods.getGoodsId());
        marketComment.setContent(orderCommentBo.getContent());
        marketComment.setHasPicture(orderCommentBo.isHasPicture());
        marketComment.setPicUrls(orderCommentBo.getPicUrls());
        marketComment.setStar(orderCommentBo.getStar());
        marketComment.setType((byte) 0);
        marketComment.setAddTime(new Date());
        marketComment.setUpdateTime(new Date());
        marketComment.setUserId(primaryPrincipal.getId());
        int code = marketCommentMapper.insertSelective(marketComment);
        if (code == 0) {
            return 0;
        }
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(marketOrderGoods.getOrderId());
        marketOrder.setComments((short) 1);
        marketOrder.setUpdateTime(new Date());
        int code1 = marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        return code1;
    }


    // 取消订单将订单状态码设置为102
    @Override
    public void cancelOrderById(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        Short status = 102;
        marketOrder.setOrderStatus(status);

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    // 提交订单
    @Override
    public OrderSubmitVo submitOrder(OrderSubmitBo orderSubmitBo) {
        // 根据地址id查找地址的信息
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(orderSubmitBo.getAddressId());

        MarketOrder marketOrder = new MarketOrder();

        // 添加订单的地址信息
        if (marketAddress != null){
            // 订单地址
            String address = marketAddress.getProvince() + marketAddress.getCity()
                    + marketAddress.getCounty() + marketAddress.getAddressDetail();
            marketOrder.setAddress(address);
            // 订单手机号
            marketOrder.setMobile(marketAddress.getTel());

            // 订单信息
            marketOrder.setMessage(orderSubmitBo.getMessage());
        }

        // 通过cartId查找对应的cart中的信息
        ArrayList<MarketCart> marketCarts = null;
        BigDecimal price = BigDecimal.valueOf(0.0);

        // 设置订单商品集合
        ArrayList<MarketOrderGoods> goodsIds = new ArrayList<>();

        // 在购物车中下单的
        if (orderSubmitBo.getCartId() == 0){
            Short check = 1;
            marketCarts = marketCartMapper.selectByCheck(check);
            // 删除购物车中的订单
            for (MarketCart marketCart : marketCarts) {
                price = marketCart.getPrice().add(price);
                marketCartMapper.deleteByPrimaryKey(marketCart.getId());
                // 获取购物车中的商品信息 将其插入到订单商品表中
                MarketOrderGoods goods = new MarketOrderGoods();
                goods.setDeleted(false);
                goods.setGoodsId(marketCart.getGoodsId());
                goods.setGoodsName(marketCart.getGoodsName());
                goods.setGoodsSn(marketCart.getGoodsSn());
                goods.setProductId(marketCart.getProductId());
                goods.setPicUrl(marketCart.getPicUrl());
                goods.setNumber(marketCart.getNumber());
                goods.setPrice(marketCart.getPrice());
                goods.setSpecifications(marketCart.getSpecifications().toString());
                goods.setDeleted(marketCart.getDeleted());
                goods.setAddTime(new Date());
                goods.setUpdateTime(new Date());

                goodsIds.add(goods);
            }
        }else{
            marketCarts = marketCartMapper.selectByCartId(orderSubmitBo.getCartId());
            for (MarketCart marketCart : marketCarts) {
                price = marketCart.getPrice().add(price);
                // 获取购物车中的商品信息 将其插入到订单商品表中
                MarketOrderGoods goods = new MarketOrderGoods();
                goods.setDeleted(false);
                goods.setGoodsId(marketCart.getGoodsId());
                goods.setGoodsName(marketCart.getGoodsName());
                goods.setGoodsSn(marketCart.getGoodsSn());
                goods.setProductId(marketCart.getProductId());
                goods.setPicUrl(marketCart.getPicUrl());
                goods.setNumber(marketCart.getNumber());
                goods.setPrice(marketCart.getPrice());
                goods.setSpecifications(marketCart.getSpecifications().toString());
                goods.setDeleted(marketCart.getDeleted());
                goods.setAddTime(new Date());
                goods.setUpdateTime(new Date());

                goodsIds.add(goods);
            }
        }
        // 设置商品价格
        marketOrder.setGoodsPrice(price);

        // 设置订单中的userId
        Integer userId = marketCarts.get(0).getUserId();
        marketOrder.setUserId(userId);

        MarketUser user = marketUserMapper.selectByPrimaryKey(userId);

        marketOrder.setConsignee(user.getUsername());

        BigDecimal price2 = BigDecimal.valueOf(0);

        marketOrder.setFreightPrice(price2);
        marketOrder.setCouponPrice(price2);
        marketOrder.setIntegralPrice(price2);
        marketOrder.setGrouponPrice(price2);


        // 通过userCouponId 查询对应的优惠券信息
        MarketCouponUser marketUserCoupon = marketCouponUserMapper.selectByPrimaryKey(orderSubmitBo.getUserCouponId());

        BigDecimal couponPrice = null;


        MarketCouponUser marketCouponUser = null;
        if (marketUserCoupon != null){

            // 查询对应的优惠券信息
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketUserCoupon.getCouponId());

            couponPrice = marketCoupon.getDiscount();
            // 设置优惠券减少金额
            marketOrder.setCouponPrice(couponPrice );

            // 修改对应的用户优惠券的信息
            marketCouponUser = new MarketCouponUser();
            marketCouponUser.setId(orderSubmitBo.getUserCouponId());
            marketCouponUser.setUpdateTime(new Date());
            marketCouponUser.setUsedTime(new Date());

            Short status = 1;
            marketCouponUser.setStatus(status);

        }

        // 实际价格
        BigDecimal actual = price;
        if (couponPrice != null){
            actual = actual.subtract(couponPrice);
        }
        marketOrder.setOrderPrice(actual);
        marketOrder.setActualPrice(actual);

        marketOrder.setAddTime(new Date());
        marketOrder.setPayTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrder.setDeleted(false);

        // 设置订单编号，用日期来设置
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String orderSn = simpleDateFormat.format(date);
        String s1 = orderSn.replace(":", "").replace("-", "").replace(" ", "");
        marketOrder.setOrderSn(s1);



        // 设置售后状态
        Short status = 0;
        marketOrder.setAftersaleStatus(status);


        Short orderStatus = 201;
        marketOrder.setOrderStatus(orderStatus);
        marketOrderMapper.insert(marketOrder);

        // 向商品订单表中插入商品
        for (MarketOrderGoods goodsId : goodsIds) {
            goodsId.setOrderId(marketOrder.getId());

            marketOrderGoodsMapper.insertSelective(goodsId);
        }

        // 修改用户优惠券表中的信息
        if(marketCouponUser != null){
            marketCouponUser.setOrderId(marketOrder.getId());
            marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);
        }


        OrderSubmitVo submitVo = new OrderSubmitVo();
        submitVo.setGrouponLinkId(0);
        submitVo.setOrderId(marketOrder.getId());
        return submitVo;
    }

    // 订单付款 修改订单状态码为201
    @Override
    public void updateOrderStatus(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();

        marketOrder.setId(orderId);
        marketOrder.setUpdateTime(new Date());
        Short status = 201;
        marketOrder.setOrderStatus(status);
        marketOrder.setPayTime(new Date());

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

    }
}
